// BagPanel.ts - 重构版本
import { _decorator, Component, Node, Sprite, Label, Button, ScrollView, Prefab, instantiate, Color, Widget, UITransform, Layout, Size, view } from 'cc';
import { GameDataService } from './GameDataService';
import { InventoryItem } from './GameDataModels';
const { ccclass, property } = _decorator;

@ccclass('BagPanel')
export class BagPanel extends Component {
    @property({ type: Button })
    closeButton: Button | null = null;

    @property({ type: Button })
    equipmentTab: Button | null = null;

    @property({ type: Button })
    materialTab: Button | null = null;

    @property({ type: Button })
    itemTab: Button | null = null;

    @property({ type: ScrollView })
    scrollView: ScrollView | null = null;

    @property({ type: Prefab })
    itemSlotPrefab: Prefab | null = null;

    @property({ type: Node })
    contentNode: Node | null = null;

    // 底部详情面板组件
    @property({ type: Node })
    itemDetailPanel: Node | null = null;

    @property({ type: Label })
    itemNameLabel: Label | null = null;

    @property({ type: Label })
    itemDescLabel: Label | null = null;

    private dataService: GameDataService;
    private currentTab: string = 'equipment';
    private currentSelectedItem: InventoryItem | null = null;

    // 添加选中状态颜色常量
    private readonly SELECTED_COLOR = new Color(255, 220, 50, 255);    // 金色边框
    private readonly NORMAL_COLOR = new Color(150, 150, 150, 200);     // 默认边框颜色
    
    // 当前选中的物品槽节点
    private currentSelectedSlot: Node | null = null;

    onLoad() {
        this.dataService = GameDataService.getInstance();
        this.setupPanel();
        this.setupScrollView(); // 添加ScrollView设置
    }

    start() {
        this.bindEvents();
        this.showTab('equipment');
        this.clearItemDetail(); // 初始清空详情
    }

    // 设置ScrollView
    setupScrollView() {
        if (!this.scrollView) {
            console.error("ScrollView未设置");
            return;
        }

        console.log("📏 ScrollView设置检查:");
        console.log("- View大小:", this.scrollView.node.getComponent(UITransform)?.contentSize);
        console.log("- Content大小:", this.scrollView.content?.getComponent(UITransform)?.contentSize);

        // 确保ScrollView启用滚动
        this.scrollView.vertical = true;
        this.scrollView.horizontal = false;
        this.scrollView.inertia = true;
        this.scrollView.brake = 0.7;

        // 设置滚动条
        if (this.scrollView.verticalScrollBar) {
            this.scrollView.verticalScrollBar.enabled = true;
        }
    }

    showItems() {
        if (!this.contentNode || !this.itemSlotPrefab) return;

        this.contentNode.removeAllChildren();

        const inventory = this.dataService.getInventory();
        const filteredItems = this.filterItemsByTab(inventory);

        if (filteredItems.length === 0) {
            this.showEmptyHint();
            // 确保空内容时也重置滚动
            this.scheduleOnce(() => {
                this.scrollToTop();
            }, 0);
            return;
        }

        filteredItems.forEach((item, index) => {
            const itemSlot = instantiate(this.itemSlotPrefab);
            if (itemSlot && this.contentNode) {
                this.contentNode.addChild(itemSlot);
                this.setupItemSlot(itemSlot, item, index);
            }
        });

        // 确保布局更新
        this.scheduleOnce(() => {
            this.updateContentLayout();
            // 添加滚动到顶部的调用
            this.scrollToTop();
        }, 0);
    }

    // 添加滚动到顶部的方法
    scrollToTop() {
        if (this.scrollView) {
            this.scrollView.scrollToTop(0);
            console.log("滚动条已重置到顶部");
        }
    }

    // 关键修复：更新内容布局
    updateContentLayout() {
        if (!this.contentNode) return;

        // 确保有Layout组件
        let layout = this.contentNode.getComponent(Layout);
        if (!layout) {
            layout = this.contentNode.addComponent(Layout);
            layout.type = Layout.Type.GRID;
            layout.cellSize = new Size(100, 100);
            layout.spacingX = 15;
            layout.spacingY = 15;
            layout.startAxis = Layout.AxisDirection.HORIZONTAL;
        }

        layout.updateLayout();

        // 设置正确的内容大小
        const uiTransform = this.contentNode.getComponent(UITransform);
        if (uiTransform) {
            const children = this.contentNode.children;
            if (children.length > 0) {
                const rows = Math.ceil(children.length / 5); // 假设每行4个
                const neededHeight = rows * 110 + (rows - 1) * 20;
                uiTransform.setContentSize(uiTransform.contentSize.width, Math.max(neededHeight, 400));
            }
        }

        // 添加滚动到顶部的调用
        this.scheduleOnce(() => {
            this.scrollToTop();
        }, 0.1);
    }

    // 调整Content大小以适应内容
    adjustContentSize(itemCount: number) {
        if (!this.contentNode || !this.scrollView) return;

        const uiTransform = this.contentNode.getComponent(UITransform);
        const scrollViewTransform = this.scrollView.node.getComponent(UITransform);
        
        if (!uiTransform || !scrollViewTransform) return;

        // 计算需要的高度（假设每个物品格子高度为120px，间距为15px）
        const itemHeight = 120;
        const spacing = 15;
        const rows = Math.ceil(itemCount / 4); // 假设每行4个
        const neededHeight = rows * itemHeight + (rows - 1) * spacing;

        // 设置content高度
        const viewHeight = scrollViewTransform.contentSize.height;
        uiTransform.setContentSize(uiTransform.contentSize.width, Math.max(neededHeight, viewHeight));

        console.log("📐 Content大小调整:", {
            物品数量: itemCount,
            需要高度: neededHeight,
            视图高度: viewHeight,
            最终高度: uiTransform.contentSize.height
        });
    }

    // 刷新ScrollView
    refreshScrollView() {
        if (this.scrollView) {
            // 强制刷新布局
            const layout = this.contentNode?.getComponent(Layout);
            if (layout) {
                layout.updateLayout();
            }
            
            // 重置滚动位置
            this.scrollView.scrollToTop(0);
        }
    }

    setupPanel() {
        // 全屏适配
        const widget = this.node.getComponent(Widget) || this.node.addComponent(Widget);
        widget.isAlignLeft = widget.isAlignRight = widget.isAlignTop = widget.isAlignBottom = true;
        widget.left = widget.right = widget.top = widget.bottom = 0;
    }

    bindEvents() {
        // 返回按钮
        if (this.closeButton) {
            this.closeButton.node.on(Button.EventType.CLICK, this.onClose, this);
        }

        // Tab按钮
        if (this.equipmentTab) {
            this.equipmentTab.node.on(Button.EventType.CLICK, () => this.showTab('equipment'), this);
        }

        if (this.materialTab) {
            this.materialTab.node.on(Button.EventType.CLICK, () => this.showTab('material'), this);
        }

        if (this.itemTab) {
            this.itemTab.node.on(Button.EventType.CLICK, () => this.showTab('item'), this);
        }
    }

    onClose() {
        if (this.node && this.node.isValid) {
            this.node.destroy();
        }
    }

    showTab(tabName: string) {
        this.currentTab = tabName;
        this.updateTabButtons();
        this.clearItemDetail(); // 切换标签时清空详情
        this.showItems();
    }

    updateTabButtons() {
        const tabs = [
            { button: this.equipmentTab, name: 'equipment' },
            { button: this.materialTab, name: 'material' },
            { button: this.itemTab, name: 'item' }
        ];

        tabs.forEach(tab => {
            if (tab.button && tab.button.node) {
                const label = tab.button.node.getComponentInChildren(Label);
                if (label) {
                    if (this.currentTab === tab.name) {
                        label.color = Color.WHITE;
                        tab.button.interactable = false;
                        const bgSprite = tab.button.node.getComponent(Sprite);
                        if (bgSprite) {
                            bgSprite.color = new Color(60, 100, 200);
                        }
                    } else {
                        label.color = new Color(200, 200, 200);
                        tab.button.interactable = true;
                        const bgSprite = tab.button.node.getComponent(Sprite);
                        if (bgSprite) {
                            bgSprite.color = new Color(80, 80, 120);
                        }
                    }
                }
            }
        });
    }

    filterItemsByTab(items: InventoryItem[]): InventoryItem[] {
        switch (this.currentTab) {
            case 'equipment': return items.filter(item => item.type === 'equipment');
            case 'material': return items.filter(item => item.type === 'material');
            case 'item': return items.filter(item => item.type === 'consumable');
            default: return items;
        }
    }

    setupItemSlot(itemSlot: Node, item: InventoryItem, index: number) {
        // 设置数量显示
        const countLabel = itemSlot.getChildByName('CountLabel');
        if (countLabel) {
            const labelComp = countLabel.getComponent(Label);
            if (labelComp) {
                if (item.count > 1) {
                    labelComp.string = item.count.toString();
                    countLabel.active = true;
                } else {
                    countLabel.active = false;
                }
            }
        }

        // 设置图标占位符（显示物品名称首字）
        const iconLabel = itemSlot.getChildByName('IconLabel');
        if (iconLabel) {
            const labelComp = iconLabel.getComponent(Label);
            if (labelComp && item.name.length > 0) {
                labelComp.string = item.name.charAt(0);
                // 根据类型设置文字颜色
                labelComp.color = this.getItemColorByType(item.type);
            }
        }

        // 设置背景色
        const bgSprite = itemSlot.getComponent(Sprite);
        if (bgSprite) {
            bgSprite.color = this.getItemBgColorByType(item.type);
        }

        // // 添加或获取边框节点
        // let borderNode = itemSlot.getChildByName('SelectedBorder');
        // if (!borderNode) {
        //     borderNode = new Node('SelectedBorder');
        //     const borderSprite = borderNode.addComponent(Sprite);
        //     // 这里您需要设置边框图片资源，或者使用纯色
        //     borderSprite.color = this.NORMAL_COLOR;
        //     borderNode.setPosition(0, 0);
        //     itemSlot.addChild(borderNode);
            
        //     // 设置边框大小略大于物品槽
        //     const uiTransform = borderNode.addComponent(UITransform);
        //     uiTransform.setContentSize(110, 110); // 比物品槽大10px
        // }
        // else {
        //     // 如果边框已存在，只需要更新颜色
        //     const borderSprite = borderNode.getComponent(Sprite);
        //     if (borderSprite) {
        //         borderSprite.color = this.NORMAL_COLOR;
        //     }
        // }

        // 初始设置为未选中状态
        this.setItemSelected(itemSlot, false);

        // 添加点击事件
        let button = itemSlot.getComponent(Button);
        if (!button) {
            button = itemSlot.addComponent(Button);
        }
        
        button.node.off(Button.EventType.CLICK);
        button.node.on(Button.EventType.CLICK, () => {
            this.onItemClick(item, itemSlot);
        }, this);
    }

    onItemClick(item: InventoryItem, itemSlot: Node) {
        console.log(`点击物品: ${item.name}`);
        // 取消之前选中的物品
        if (this.currentSelectedSlot && this.currentSelectedSlot.isValid) {
            this.setItemSelected(this.currentSelectedSlot, false);
        }
        
        // 设置当前选中的物品
        this.setItemSelected(itemSlot, true);
        this.currentSelectedSlot = itemSlot;
        this.currentSelectedItem = item;
        
        this.showItemDetail(item);
    }

    // 设置物品选中状态的方法
    setItemSelected(itemSlot: Node, isSelected: boolean) {
        const borderNode = itemSlot.getChildByName('SelectedBorder');
        if (borderNode) {
            const borderSprite = borderNode.getComponent(Sprite);
            if (borderSprite) {
                if (isSelected) {
                // 选中状态 - 金色边框
                borderSprite.color = this.SELECTED_COLOR;
                borderNode.active = true;
            } else {
                // 未选中状态 - 可以根据需要隐藏或显示默认边框
                borderSprite.color = this.NORMAL_COLOR;
                borderNode.active = false; // 或者设置为 true 但颜色不同
            }
            }
        }
        
        // // 可选：添加缩放效果
        // if (isSelected) {
        //     itemSlot.setScale(1.1, 1.1);
        // } else {
        //     itemSlot.setScale(1, 1);
        // }
    }

    // 显示物品详情在底部面板
    showItemDetail(item: InventoryItem) {
        if (!this.itemDetailPanel) return;

        this.currentSelectedItem = item;
        this.updateDetailContent(item);
    }

    // 清空物品详情
    clearItemDetail() {
        // 取消选中状态
        if (this.currentSelectedSlot && this.currentSelectedSlot.isValid) {
            this.setItemSelected(this.currentSelectedSlot, false);
        }
        this.currentSelectedSlot = null;
        this.currentSelectedItem = null;
        if (this.itemNameLabel) this.itemNameLabel.string = "请选择物品";
        if (this.itemDescLabel) this.itemDescLabel.string = "点击上方物品查看详情";
    }

    // 更新详情内容
    updateDetailContent(item: InventoryItem) {
        if (!this.itemNameLabel || !this.itemDescLabel) return;

        // 物品名称
        this.itemNameLabel.string = item.name;
        this.itemNameLabel.color = this.getItemColorByType(item.type);

        // 详细描述
        let description = "";
        
        if (item.description) {
            description += `📝 ${item.description}\n\n`;
        }

        // 根据物品类型添加额外信息
        switch(item.type) {
            case 'equipment':
                description += "⚔️ 装备属性:\n• 可装备使用\n• 提供战斗加成";
                break;
            case 'material':
                description += "🛠️ 材料用途:\n• 用于合成制作\n• 可出售换取金币";
                break;
            case 'consumable':
                description += "❤️ 使用效果:\n• 即时使用物品\n• 提供各种增益效果";
                break;
            case 'pet':
                description += "🐾 宠物信息:\n• 可召唤陪伴\n• 提供辅助能力";
                break;
            case 'mount':
                description += "🏇 坐骑信息:\n• 可骑乘移动\n• 提升移动速度";
                break;
            default:
                description += "ℹ️ 物品信息:\n• 未知类型的物品";
        }

        this.itemDescLabel.string = description;
    }

    // 根据物品类型获取背景颜色
    getItemBgColorByType(type: string): Color {
        switch(type) {
            case 'equipment': return new Color(70, 70, 200, 200);    // 蓝色
            case 'material': return new Color(200, 150, 50, 200);    // 橙色
            case 'consumable': return new Color(50, 200, 100, 200);  // 绿色
            case 'pet': return new Color(255, 100, 180, 200);        // 粉色
            case 'mount': return new Color(180, 100, 255, 200);      // 紫色
            default: return new Color(100, 100, 100, 200);           // 灰色
        }
    }

    // 根据物品类型获取文字颜色
    getItemColorByType(type: string): Color {
        switch(type) {
            case 'equipment': return new Color(90, 150, 255);    // 亮蓝色
            case 'material': return new Color(255, 200, 50);     // 金色
            case 'consumable': return new Color(50, 220, 100);   // 亮绿色
            case 'pet': return new Color(255, 100, 180);         // 粉红色
            case 'mount': return new Color(180, 100, 255);       // 紫色
            default: return Color.WHITE;
        }
    }

    showEmptyHint() {
        if (!this.contentNode) return;

        const hintLabel = new Node();
        const labelComp = hintLabel.addComponent(Label);
        labelComp.string = `当前${this.getTabChineseName()}为空`;
        labelComp.fontSize = 24;
        labelComp.color = Color.GRAY;
        labelComp.horizontalAlign = Label.HorizontalAlign.CENTER;
        labelComp.verticalAlign = Label.VerticalAlign.CENTER;
        
        this.contentNode.addChild(hintLabel);
    }

    getTabChineseName(): string {
        switch (this.currentTab) {
            case 'equipment': return '装备';
            case 'material': return '材料';
            case 'item': return '道具';
            default: return '物品';
        }
    }

    getTypeName(type: string): string {
        const typeMap: { [key: string]: string } = {
            'equipment': '装备',
            'material': '材料', 
            'consumable': '道具',
            'pet': '宠物',
            'mount': '坐骑'
        };
        return typeMap[type] || '未知';
    }

    onDestroy() {
        console.log("BagPanel组件被销毁");
        // 清理引用
        this.currentSelectedSlot = null;
        this.currentSelectedItem = null;
    }
}